package org.mili.ticketeer.report;

import org.apache.commons.io.FileUtils;
import org.mili.core.templating.TemplateStore;
import org.mili.ticketeer.dto.Contact;
import org.mili.ticketeer.dto.Role;
import org.mili.ticketeer.service.ServiceException;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class FunctionalListGenerator extends AbstractGenerator {
    public FunctionalListGenerator(ReportEngine reportEngine, TemplateStore templateStore) {
        super(reportEngine, templateStore);
    }

    public void generate() throws IOException, ServiceException {
        System.out.println("generate");
        StringBuilder s1 = new StringBuilder();
        String temp = templateStore.get("functional_Groups");
        for(Map.Entry<Role, List<Contact>> entry : reportEngine.getGroupRoles().entrySet()) {
            StringBuilder s3 = new StringBuilder();
            for(Contact contact : entry.getValue()) {
                if (contact.isActive()) {
                    String temp2 = templateStore.get("functional_Speaker");
                    s3.append(temp2.replace("${sex}", reportEngine.printSex(contact.getSex()))
                            .replace("${lastname}", reportEngine.getHtml(contact.getLastName()))
                    );
                }
            }
            s1.append(temp.replace("${group}", reportEngine.getHtml(entry.getKey().getName()))
                    .replace("${Speaker}", s3)
            );
        }

        StringBuilder s2 = new StringBuilder();
        Map<Role, Contact> single = reportEngine.getSingleRoles();
        temp = templateStore.get("functional_Single");
        String empty = templateStore.get("functional_Empty");
        int i = 0;
        for(Map.Entry<Role, Contact> entry : single.entrySet()) {
            i ++;
            Contact contact = entry.getValue();
            if (contact.isActive()) {
                s2.append(
                        temp.replace("${role}", reportEngine.getHtml(entry.getKey().getName()))
                        .replace("${sex}", reportEngine.printSex(contact.getSex()))
                        .replace("${lastname}", reportEngine.getHtml(contact.getLastName()))
                        .replace("${Empty}", i % 2 == 0 ? empty : "")
                );
            }
        }

        SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
        FileUtils.writeStringToFile(new File("./tmp/out/ausschuesse.html"),
                templateStore.get("functional_Main")
                        .replace("${Groups}", s1)
                        .replace("${Single}", s2)
                        .replace("${date}", format.format(new Date()))
                        .replace("${title}", "")
        );
    }

}
